package com.l.im.mq;


import com.alibaba.fastjson.JSON;
import com.l.im.common.api.ApiResponse;
import com.l.im.model.SingleMessageDTO;
import com.l.im.service.handler.MessageDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.MessageListener;
import org.apache.rocketmq.client.apis.message.MessageView;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

@Slf4j
public class SingleMessageListener implements MessageListener {

    @Override
    public ConsumeResult consume(MessageView messageView) {
        String messageId = messageView.getMessageId().toString();
        ByteBuffer body = messageView.getBody();
        String bodyStr = StandardCharsets.UTF_8.decode(body).toString();
        log.info("Received MQ message: id={}, body={}", messageId, bodyStr);

        SingleMessageDTO singleMessageDTO = JSON.parseObject(bodyStr, SingleMessageDTO.class);

        String toUserId = singleMessageDTO.getToUserId();
        MessageDispatcher.sendToUser(toUserId,
                    ApiResponse.success(singleMessageDTO));


        return ConsumeResult.SUCCESS;
    }
}
